package org.hepeng.workx.spring.cloud.netflix.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import java.util.List;

/**
 * @author he peng
 */
public class ZuulResponseWriterHeaderFilter extends ZuulFilter {

    private List<HeaderWriter> headerWriters;

    public ZuulResponseWriterHeaderFilter(List<HeaderWriter> headerWriters) {
        this.headerWriters = headerWriters;
    }


    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        if (CollectionUtils.isNotEmpty(headerWriters)) {
            for (HeaderWriter headerWriter : headerWriters) {
                headerWriter.writeHeaders(RequestContext.getCurrentContext());
            }
        }
        return null;
    }

    public interface HeaderWriter {
        void writeHeaders(RequestContext requestContext);
    }
}
